# import sys
# import os
# import re
# from datetime import datetime

from flask import Blueprint, render_template, redirect, request, Response, send_file, send_from_directory, jsonify, url_for
from flask_login import LoginManager, login_user, logout_user, current_user, login_required
from router.models import User, query_user

import configparser
import json
import threading
import time
import paho.mqtt.client as mqtt

# import csv
# import sqlite3
# import openpyxl
# from openpyxl import load_workbook,Workbook


# here define a route
module_bp = Blueprint(
    'module',
    '__name__',
)

IOT_TEMP = 0
IOT_HUMI = 0
IOT_STATUS = 0


##################################################
# SETTINGS
##################################################
@module_bp.route('/')
@module_bp.route('/setting')
@login_required
def setting():
    return render_template('setting.html', title='系统设置', curr_user=current_user.get_id())


# cf = configparser.ConfigParser()
# cf.read("Config.ini")
# SER_PORT = cf.get("dev", "port")
# SER_BAUDRATE = cf.getint("device", "baudrate")
# GUI_VER = cf.get("GUI Info","Version")


@module_bp.route('/api/get_mqtt_server_settings', methods=['POST'])
def get_mqtt_server_settings():
    print('get_mqtt_server_settings ...')
    config = {}
    with open("mqtt-iot-lite.json",'r') as load_f:
        config = json.load(load_f)
        print(config)
 
    return json.dumps(config)


@module_bp.route('/api/set_mqtt_server_settings', methods=['POST'])
def set_mqtt_server_settings():
    print('set_mqtt_server_settings ...')
    address_val = request.form["address_val"]
    port_val = request.form["port_val"]
    
    config = {}

    config.update(
        {
        'address_val': address_val,
        'port_val': port_val
        }
    )
    with open("mqtt-iot-lite.json", "w") as f:
        json.dump(config, f, indent=4, ensure_ascii=False)
	 
    return "Set successfully."


@module_bp.route('/api/btn_add_component_settings', methods=['POST'])
def btn_add_component_settings():
    print('btn_add_component_settings ...')
    sub_name = request.form["sub_name"]
    min_val = request.form["min_val"]
    max_val = request.form["max_val"]
    color_val = request.form["color_val"]
        
    with open("mqtt-iot-lite.json",'r') as load_f:
        config = json.load(load_f)
        print(config)
 
    config.update(
        {
            sub_name: {
                'min': min_val,
                'max': max_val,
                'color': color_val
            }
        }
    )

    with open("mqtt-iot-lite.json", "w+") as f:
        json.dump(config, f, indent=4, ensure_ascii=False)
	 
    return "Set successfully."


@module_bp.route('/api/btn_subscribe', methods=['POST'])
def btn_subscribe():
    print('btn_subscribe ...')
    mqtt_t = threading.Thread(target=mqtt_sub, args=('mqtt_sub_task', 1,))
    mqtt_t.start()
    return "mqtt_t start ...."


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("connect ok")
        print("Connected with result code " + str(rc))
        global IOT_STATUS 
        IOT_STATUS = 1
        

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))
    print(msg.payload)
    print(type(msg.payload))
    if msg.topic == 'Kzeng-Pub-Temp':
        global IOT_TEMP 
        IOT_TEMP = str(float(msg.payload))

    if msg.topic == 'Kzeng-Pub-Humi':
        global IOT_HUMI
        IOT_HUMI = str(float(msg.payload))


# https://zhuanlan.zhihu.com/p/187481769
def mqtt_sub(tname, delay):
    print('start mqtt task: ' + tname)
    time.sleep(delay)

    client = mqtt.Client(protocol=3)
    # client.username_pw_set("admin", "password")
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(host="118.31.36.131", port = 1883, keepalive=60)  # 订阅频道
    time.sleep(2)
    # client.subscribe("public")
    # client.subscribe([("public", 0), ("test", 2)])
    client.subscribe([('Kzeng-Pub-Temp', 0), ('Kzeng-Pub-Humi', 0)])
    client.loop_forever()

        
@module_bp.route('/api/iot_get_info', methods=['POST'])
def iot_get_info():
    print('iot_get_info ...')
    iot_dict = {}
    iot_dict.update(
        {
            'temp': IOT_TEMP,
            'humi': IOT_HUMI,
            'iot_status': IOT_STATUS,
        }
    )
    return json.dumps(iot_dict)



